﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.Web;

namespace DemoApp1.Common
{
    public class CWPrincipal : IPrincipal
    {
        private IIdentity _identity = null;

        [DataMember]
        public int UserID
        {
            get;
            set;
        }

        [DataMember]
        public string UserName
        {
            get;
            set;
        }

        [DataMember]
        public string CName
        {
            get;
            set;
        }

        [DataMember]
        public List<string> Roles
        {
            get;
            set;
        }

        [DataMember]
        public int BusinessUnitID
        {
            get;
            set;
        }

        [DataMember]
        public List<int> AuthorizedBusinessUnitID
        {
            get;
            set;
        }

        public IIdentity Identity
        {
            //, ClientConfig.ClientId + "_FormAuthentication"
            get { return _identity ?? (_identity = new GenericIdentity(UserName)); }
        }

        public bool IsInRole(string role)
        {
            return Roles.Contains(role);
        }

        public bool IsRole(string role, bool checkOnly)
        {
            if (checkOnly)
            {
                return Roles.Count == 1 && string.Compare(Roles[0], role, true) == 0;
            }

            return Roles.Contains(role);
        }

        /// <summary>
        /// Get's a JSON serialized string of a SimplePrincipal object
        /// </summary>
        public static string GetCookieUserData(CWPrincipal principal)
        {
            return JsonHelper.JsonSerializer<CWPrincipal>(principal);
        }

        /// <summary>
        /// Creates a SimplePrincipal object using a JSON string from the asp.net auth cookie
        /// </summary>
        public static CWPrincipal CreatePrincipalFromCookieData(string userData)
        {
            CWPrincipal principal = JsonHelper.JsonDeserialize<CWPrincipal>(userData);
            return principal;
        }
    }
}